const gulp = require('gulp'),
      htmlmin = require('gulp-htmlmin'),
      cleanCss = require('gulp-clean-css'),
      autoprefixer = require('gulp-autoprefixer'),
      uglify = require('gulp-uglify'),
      babel = require('gulp-babel'),
      del = require('del'),
      connect = require('gulp-connect'),
      sass = require('gulp-sass'),
      proxy = require('http-proxy-middleware')

const paths = {
  html:{
    src:'src/**/*.html',
    dest:'dist'
  },
  css:{
    src:'src/css/**/*.scss',
    dest:'dist/css'
  },
  js:{
    src:'src/js/**/*.js',
    dest:'dist/js'
  },
  img:{
    src:'src/images/**/*',
    dest:'dist/images'
  },
  libs:{
    src:'src/libs/**/*',
    dest:'dist/libs'
  }
}

const delDist = () => {
  return del(['dist'])
}

const html = () => {
  return gulp.src(paths.html.src)
  .pipe(htmlmin({
    removeComments:true,
    collapseWhitespace:true,
    collapseBooleanAttributes:true,
    removeEmptyAttributes:true,
    removeScriptTypeAttributes:false,
    removeStyleLinkTypeAttributes:true,
    minifyJS:true,
    minifyCSS:true
  }))
  .pipe(gulp.dest(paths.html.dest))
  .pipe(connect.reload())
}

const css = () => {
  return gulp.src(paths.css.src)
  .pipe(sass())
  .pipe(autoprefixer({
    overrideBrowserslist:['last 2 versions']
  }))
  // .pipe(cleanCss())
  .pipe(gulp.dest(paths.css.dest))
  .pipe(connect.reload())
}

const js = () => {
  return gulp.src(paths.js.src)
  .pipe(babel({
    presets:['@babel/env']
  }))
  .pipe(uglify())
  .pipe(gulp.dest(paths.js.dest))
  .pipe(connect.reload())
}

const img = () => {
  return gulp.src(paths.img.src)
  .pipe(gulp.dest(paths.img.dest))
}

const libs = () => {
  return gulp.src(paths.libs.src)
  .pipe(gulp.dest(paths.libs.dest))
}

const server = () => {
  connect.server({
    port:8090,
    root:'dist',
    liverload:true,
    middleware: () => {
      return [
        proxy('/api',{
          target:'http://localhost:80',
          changeOrigin:true
        })
      ]
    }
  })
}

const watch = () => {
  gulp.watch(paths.html.src,html)
  gulp.watch(paths.css.src,css)
  gulp.watch(paths.js.src,js)
}

/* module.exports = {
  html,
  css,
  js,
  img,
  libs
} */

module.exports.default = gulp.series(delDist,gulp.parallel(server,html,js,css,img,libs,watch))